/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MonthEnd.java
 *
 * Created on 28-Aug-2010, 15:37:03
 */

package TimeRecording.forms;

import TimeRecording.business.DaisyChainUtilities;
import TimeRecording.business.HolidayCalculations;
import TimeRecording.business.MonthEndCalculations;
import TimeRecording.business.SicknessCalculations;
import TimeRecording.enums.MonthStatus;
import TimeRecording.tables.MonthlyControl;
import java.awt.Cursor;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;

/**
 *
 * @author david
 */
public class MonthEndProcessingDialog extends javax.swing.JDialog {

    private EntityManager entityManager;

    /** Creates new form MonthEnd */
    public MonthEndProcessingDialog(java.awt.Frame parent,
            EntityManager entityManager) {

        super(parent, true);
        initComponents();
        this.entityManager = entityManager;

        // Default the period to the start and end of this month
        fromDate.setDate(DaisyChainUtilities.firstDayOfMonth(null).getTime());
        cutOffDate.setDate(DaisyChainUtilities.lastDayOfMonth(null).getTime());
        fromDate.setEnabled(true);

        sessionalFromDate.setDate(DaisyChainUtilities.firstDayOfMonth(null).getTime());
        sessionalCutOffDate.setDate(DaisyChainUtilities.lastDayOfMonth(null).getTime());
        sessionalFromDate.setEnabled(true);

        MonthlyControl latestMonth = MonthlyControl.getLatest(entityManager);

        if (latestMonth != null) {
            if (latestMonth.getStatus() == MonthStatus.IN_PROGRESS) {

                // This month is still "open" so allow the end date to be changed

                fromDate.setEnabled(false);
                fromDate.setDate(latestMonth.getStartDate());
                cutOffDate.setDate(latestMonth.getEndDate());

                sessionalFromDate.setEnabled(false);
                sessionalFromDate.setDate(latestMonth.getSessionalStartDate());
                sessionalCutOffDate.setDate(latestMonth.getSessionalEndDate());
                return;

            } else {

                // "This" month is closed so probably want to start a new
                // month on the day after the end of the previous month

                GregorianCalendar cal = new GregorianCalendar();

                cal.setTime(latestMonth.getEndDate());
                cal.add(GregorianCalendar.DATE, 1);
                fromDate.setDate(cal.getTime());
                fromDate.setEnabled(false);

                cal.setTime(latestMonth.getSessionalEndDate());
                cal.add(GregorianCalendar.DATE, 1);
                sessionalFromDate.setDate(cal.getTime());
                sessionalFromDate.setEnabled(false);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialise the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        progress = new javax.swing.JProgressBar();
        buttonPanel = new javax.swing.JPanel();
        processButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        nonSessionalPanel = new javax.swing.JPanel();
        fromDateLabel = new javax.swing.JLabel();
        fromDate = new com.toedter.calendar.JDateChooser();
        cutOffDateLabel = new javax.swing.JLabel();
        cutOffDate = new com.toedter.calendar.JDateChooser();
        sessionalPanel = new javax.swing.JPanel();
        sessionalFromDateLabel = new javax.swing.JLabel();
        sessionalFromDate = new com.toedter.calendar.JDateChooser();
        sessionalCutOffDateLabel1 = new javax.swing.JLabel();
        sessionalCutOffDate = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(MonthEndProcessingDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        progress.setName("progress"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(progress, gridBagConstraints);

        buttonPanel.setName("buttonPanel"); // NOI18N

        processButton.setText(resourceMap.getString("processButton.text")); // NOI18N
        processButton.setName("processButton"); // NOI18N
        processButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                processButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(processButton);

        closeButton.setText(resourceMap.getString("closeButton.text")); // NOI18N
        closeButton.setName("closeButton"); // NOI18N
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(closeButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(buttonPanel, gridBagConstraints);

        nonSessionalPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("nonSessionalPanel.border.title"))); // NOI18N
        nonSessionalPanel.setName("nonSessionalPanel"); // NOI18N
        nonSessionalPanel.setLayout(new java.awt.GridBagLayout());

        fromDateLabel.setText(resourceMap.getString("fromDateLabel.text")); // NOI18N
        fromDateLabel.setName("fromDateLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        nonSessionalPanel.add(fromDateLabel, gridBagConstraints);

        fromDate.setMinimumSize(new java.awt.Dimension(150, 20));
        fromDate.setName("fromDate"); // NOI18N
        fromDate.setPreferredSize(new java.awt.Dimension(150, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        nonSessionalPanel.add(fromDate, gridBagConstraints);

        cutOffDateLabel.setText(resourceMap.getString("cutOffDateLabel.text")); // NOI18N
        cutOffDateLabel.setName("cutOffDateLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        nonSessionalPanel.add(cutOffDateLabel, gridBagConstraints);

        cutOffDate.setMinimumSize(new java.awt.Dimension(150, 20));
        cutOffDate.setName("cutOffDate"); // NOI18N
        cutOffDate.setPreferredSize(new java.awt.Dimension(150, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        nonSessionalPanel.add(cutOffDate, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.5;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 2, 4);
        getContentPane().add(nonSessionalPanel, gridBagConstraints);

        sessionalPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("sessionalPanel.border.title"))); // NOI18N
        sessionalPanel.setName("sessionalPanel"); // NOI18N
        sessionalPanel.setLayout(new java.awt.GridBagLayout());

        sessionalFromDateLabel.setText(resourceMap.getString("sessionalFromDateLabel.text")); // NOI18N
        sessionalFromDateLabel.setName("sessionalFromDateLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        sessionalPanel.add(sessionalFromDateLabel, gridBagConstraints);

        sessionalFromDate.setMinimumSize(new java.awt.Dimension(150, 20));
        sessionalFromDate.setName("sessionalFromDate"); // NOI18N
        sessionalFromDate.setPreferredSize(new java.awt.Dimension(150, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        sessionalPanel.add(sessionalFromDate, gridBagConstraints);

        sessionalCutOffDateLabel1.setText(resourceMap.getString("sessionalCutOffDateLabel1.text")); // NOI18N
        sessionalCutOffDateLabel1.setName("sessionalCutOffDateLabel1"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        sessionalPanel.add(sessionalCutOffDateLabel1, gridBagConstraints);

        sessionalCutOffDate.setMinimumSize(new java.awt.Dimension(150, 20));
        sessionalCutOffDate.setName("sessionalCutOffDate"); // NOI18N
        sessionalCutOffDate.setPreferredSize(new java.awt.Dimension(150, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        sessionalPanel.add(sessionalCutOffDate, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.5;
        gridBagConstraints.insets = new java.awt.Insets(2, 4, 4, 4);
        getContentPane().add(sessionalPanel, gridBagConstraints);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-417)/2, (screenSize.height-289)/2, 417, 289);
    }// </editor-fold>//GEN-END:initComponents

    private void processButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processButtonActionPerformed

        Cursor savedCursor = getCursor();

        if (cutOffDate.getDate() == null) {
            return;
        }

        try {
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            progress.setValue(0);

            entityManager.getTransaction().begin();

            new HolidayCalculations().monthEndProcessing(
                    entityManager, cutOffDate.getDate());
            
            progress.setValue(33);

            new SicknessCalculations().monthEndProcessing(
                    entityManager, cutOffDate.getDate());

            progress.setValue(66);

            MonthEndCalculations.processMonthEnd(entityManager,
                    fromDate.getDate(), cutOffDate.getDate(),
                    sessionalFromDate.getDate(), sessionalCutOffDate.getDate());

            progress.setValue(100);

            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {

            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }

            // If an error is encountered then rollback the transaction
            // and cascade the root cause back to the caller

            ErrorDialog.showError(this, e);

        } finally {
            setCursor(savedCursor);
        }
    }//GEN-LAST:event_processButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_closeButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton closeButton;
    private com.toedter.calendar.JDateChooser cutOffDate;
    private javax.swing.JLabel cutOffDateLabel;
    private com.toedter.calendar.JDateChooser fromDate;
    private javax.swing.JLabel fromDateLabel;
    private javax.swing.JPanel nonSessionalPanel;
    private javax.swing.JButton processButton;
    private javax.swing.JProgressBar progress;
    private com.toedter.calendar.JDateChooser sessionalCutOffDate;
    private javax.swing.JLabel sessionalCutOffDateLabel1;
    private com.toedter.calendar.JDateChooser sessionalFromDate;
    private javax.swing.JLabel sessionalFromDateLabel;
    private javax.swing.JPanel sessionalPanel;
    // End of variables declaration//GEN-END:variables
}
